<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue';
import { DeleteOutlined, EyeOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import {
  getImg,
  projectLinkCreateApi,
  projectLinkEditApi
} from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import { localStg } from '@/utils/storage';
const projectStore = useProjectStore();
defineOptions({
  name: 'ChainManageDrawer'
});

interface Props {
  operateType: AntDesign.TableOperateType;
  rowData?: any | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: any = {
    add: '新增外链',
    edit: '编辑外链'
  };
  return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());

function createDefaultModel(): any {
  return {};
}

const rules: any = {
  collectionNo: defaultRequiredRule,
  hostNo: defaultRequiredRule,
  hostName: defaultRequiredRule
};

/** the enabled role options */
async function handleInitModel() {
  Object.assign(model, createDefaultModel());
  imgPreview.value = '';
  if (props.operateType === 'edit' && props.rowData) {
    await nextTick();
    if (props.rowData.picName) {
      getImgPreview(props.rowData.picName);
    }
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const doAddSubmit = async () => {
  const res = await projectLinkCreateApi({
    ...model,
    projectId: projectStore.currentProject?.id
  });
  if (res.error === null) {
    window.$message?.success('新增成功');
    closeDrawer();
    emit('submitted');
  }
};
const doEditSubmit = async () => {
  const res = await projectLinkEditApi({
    ...model
  });
  if (res.error === null) {
    window.$message?.success('更新成功');
    closeDrawer();
    emit('submitted');
  }
};

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    await doAddSubmit();
  }
  if (props.operateType === 'edit') {
    await doEditSubmit();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});

/* 图片上传相关 */
const token: any = localStg.get('token');
const imgPreview: any = ref();
const loading = ref(false);
const imageVisible = ref(false);

const setVisible = (value: boolean): void => {
  imageVisible.value = value;
};

const uploadImgChange = (info: any) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    loading.value = false;
    model.picName = info.file.response.data;
    getImgPreview(info.file.response.data);
  }
  if (info.file.status === 'error') {
    loading.value = false;
    window.$message?.error('图片上传失败');
  }
};

const getImgPreview = async (fileName: any) => {
  getImg({
    fileName
  }).then((res: any) => {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      imgPreview.value = e.target.result;
    };
    reader.readAsDataURL(res.data);
  });
};

const clearImage = () => {
  imgPreview.value = '';
  model.picName = '';
};
/* 图片上传相关 */
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :mask-closable="false">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
      <AFormItem label="名称" name="name">
        <AInput v-model:value="model.name" placeholder="请输入名称" />
      </AFormItem>
      <AFormItem label="链接" name="url">
        <AInput v-model:value="model.url" placeholder="请输入链接" />
      </AFormItem>
      <AFormItem label="图标" name="picName">
        <p style="padding-bottom: 8px">图片尺寸: 1 : 1</p>
        <AUpload
          v-model:file-list="model.fileList"
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="/api/file/upload"
          :headers="{
            authorization: token
          }"
          @change="uploadImgChange"
        >
          <div v-if="imgPreview" @click.stop>
            <AImage
              :src="imgPreview"
              alt="avatar"
              :preview="{
                visible: imageVisible,
                onVisibleChange: setVisible
              }"
            >
              <template #previewMask>
                <ASpace>
                  <EyeOutlined style="font-size: 20px" @click="setVisible(true)" />
                  <DeleteOutlined style="font-size: 20px" @click="clearImage" />
                </ASpace>
              </template>
            </AImage>
          </div>
          <div v-else>
            <LoadingOutlined v-if="loading"></LoadingOutlined>
            <PlusOutlined v-else></PlusOutlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </AUpload>
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
